<template>
    <!-- 主要内容区域 -->
    <div class="flex-1 p-6 overflow-auto bg-gray-100">
        <div class="bg-white rounded-lg p-6">
            <!-- 搜索区域 -->
            <div class="flex items-center space-x-4 mb-6">
                <el-input v-model="searchForm.account" placeholder="请输入账号" class="w-64" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
                <el-input v-model="searchForm.role" placeholder="请输入角色" class="w-64" clearable>
                </el-input>
                <el-input v-model="searchForm.userName" placeholder="请输入用户名" class="w-64" clearable>
                </el-input>
                <el-select v-model="searchForm.status" placeholder="用户状态" class="w-32">
                    <el-option label="全部" value="" />
                    <el-option label="启用" value="1" />
                    <el-option label="禁用" value="0" />
                </el-select>
                <el-button type="primary" class="!rounded-button" @click="handleSearch">
                    <el-icon class="mr-1">
                        <Search />
                    </el-icon>搜索
                </el-button>
                <el-button class="!rounded-button" @click="handleReset">
                    <el-icon class="mr-1">
                        <Refresh />
                    </el-icon>重置
                </el-button>
            </div>
            <!-- 操作按钮 -->
            <div class="flex justify-between mb-4">
                <div class="space-x-2">
                    <el-button type="primary" class="!rounded-button" @click="openDialog('add')">
                        <el-icon class="mr-1">
                            <Plus />
                        </el-icon>新增
                    </el-button>
                    <el-button type="danger" class="!rounded-button whitespace-nowrap" @click="handleDelete">
                        <el-icon class="mr-1">
                            <Delete />
                        </el-icon>删除
                    </el-button>
                    <el-button type="success" class="!rounded-button" @click="handleImport">
                        <el-icon class="mr-1">
                            <Upload />
                            <input
                                    type="file"
                                    style="display: none;"
                                    ref="fileInput"
                                    @change="handleFileChange"
                            />
                        </el-icon>导入
                    </el-button>
                    <el-button type="warning" class="!rounded-button" @click="handleExport">
                        <el-icon class="mr-1">
                            <Download />
                        </el-icon>导出
                    </el-button>
                </div>
            </div>
            <!-- 表格 -->
            <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="用户编号" prop="id" width="80" />
                <el-table-column label="用户名" prop="userName" width="120" />
                <el-table-column label="用户角色" prop="role" width="120" />
                <el-table-column label="用户性别" prop="gender" width="80" >
                    <template v-slot="scope">
                        {{ scope.row.gender === 0 ? '男' : '女' }}
                    </template>
                </el-table-column>
                <el-table-column label="账号" prop="account" width="120" />
                <el-table-column label="头像" prop="userImg" width="120" >
                    <template  v-slot="scope">
                        <img :src="scope.row.userImg"  class="w-8 h-8  object-cover rounded-full overflow-hidden" />
                    </template>
                </el-table-column>
                <el-table-column label="邮箱" prop="email" width="150" />
                <el-table-column label="封禁状态" prop="status" width="80">
                    <template #default="scope">
                        <el-switch
                                v-model="form.status"
                                :active-value="1"
                                :inactive-value="0"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180" :formatter="formatDate"/>
                <el-table-column label="操作" fixed="right" width="180">
                    <template #default="scope">
                        <el-button type="primary" link @click="openDialog('edit', scope.row)">修改</el-button>
                        <el-button type="primary" link @click="handleDelete(scope.row)">删除</el-button>
                        <el-button type="primary" link @click="handleResetPassword(scope.row)">重置密码</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="flex justify-end mt-4">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :page-sizes="[10, 20, 30, 40]"
                     @current-change="getUser(pagination)"
                    layout="total, sizes, prev, pager, next, jumper" />
            </div>
        </div>
    </div>


    <!-- 新增/编辑用户弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增用户' : '编辑用户'" width="500px" destroy-on-close>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="用户名称" prop="userName">
                <el-input v-model="form.userName" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="用户角色" prop="role">
                <el-select v-model="form.role" placeholder="请选择用户角色">
                    <el-option v-for="role in roleOptions" :key="role.id" :label="role.name" :value="role.name" />
                </el-select>
            </el-form-item>
            <el-form-item label="用户头像" prop="userImg" v-if="dialogType === 'edit'">
                <el-avater v-model="form.userImg">
                </el-avater>
            </el-form-item>
            <el-form-item label="用户性别" prop="gender">
                <el-select
                        v-model="form.gender"
                        placeholder="请选择性别"
                        style="width: 100%"
                >
                    <el-option label="男" :value="0" />
                    <el-option label="女" :value="1" />
                </el-select>
            </el-form-item>
            <el-form-item label="账号" prop="account">
                <el-input v-model="form.account" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="封禁状态">
                <el-switch
                        v-model="form.status"
                        :active-value="1"
                        :inactive-value="0"
                        active-text="禁用"
                        inactive-text="启用"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit(formRef)">确认</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 上传文件弹窗 -->
    <el-upload ref="upload" :action="uploadUrl" :before-upload="beforeUpload" :on-success="handleUploadSuccess"
        :on-error="handleUploadError" accept=".xls,.xlsx" show-file-list="false" :auto-upload="false">
    </el-upload>
</template>

<script lang="ts" setup>
import { ref,onMounted } from "vue";
import * as XLSX from "xlsx";  // 引入 xlsx 库
import { FormInstance, FormRules, ElMessageBox, ElMessage } from "element-plus";
import {getAllUser,addUser,updateUser,deleteUser,uploadUser} from "../../api/admin/userManage.js";
// 选中的行的ID数组
const selectedRowKeys = ref([]);


// 日期格式化方法
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const d = new Date(cellValue);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};
const handleSelectionChange = (selection) => {
    selectedRowKeys.value = selection.map(item => item.id);
};
onMounted(()=>{
    getUser(pagination.value)
})
async function getUser(data) {
    await getAllUser(data).then(function (response) {
        tableData.value=response.items[0]
        pagination.value.total=response.total
    })
}
// 搜索栏数据
const searchForm = ref({
    keyword: '',
    username: '',
    phone: '',
    status: '',
    dateRange: [],
});

// 表格内容
let tableData = ref([]);

// 分页
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 100
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogType = ref('');
const formRef = ref<FormInstance>();
const form = ref({
    userName:"",
    role: "",
    account: "",
    userImg:"",
    email: "",
    gender: "",
    status: 0,
    id: 0 // 添加ID字段
});

// 角色下拉框
const roleOptions = ref([
    { id: 1, name: "管理员" },
    { id: 2, name: "教师" },
    { id: 3, name: "学生" },
    {id: 4, name: "招聘方"}
]);

// 打开对话框
const openDialog = (type, row) => {
    dialogType.value = type;
    if (type === 'edit' && row) {

        // 当前行为编辑模式，填充表单数据
        form.value = {
            userName: row.userName,
            role: row.role,
            userImg:row.userImg,
            account: row.account,
            gender: row.gender,
            status: row.status,
            email:row.email,
            id: row.id
        };
    } else {
        // 清空表单数据
        form.value = {
            userName: '',
            role: '',
            account: '',
            gender: 0,
            status:0,
            email:'',
            id: '' // 清空ID
        };
    }
    dialogVisible.value = true;
};
//修改与增加用户
async function add_User(data) {
    await addUser(data).then(function (response) {
        getUser(pagination.value)
    })
}
async function update_User(data) {
    await updateUser(data).then(function (response) {
        getUser(pagination.value)
    })
}
//删除用户
async function delete_User(data){
    await deleteUser(data).then(function (response) {
        getUser(pagination.value)
    })
}
// 提交表单
const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
        if (valid) {
            if (dialogType.value === 'add') {
                // 处理添加逻辑
                console.log('提交表单 - 添加', form.value);
                add_User(form.value)
                ElMessage.success('添加成功');
            } else if (dialogType.value === 'edit') {
                // 处理修改逻辑
                console.log('提交表单 - 修改', form.value);
                update_User(form.value)
                ElMessage.success('修改成功');
            }
            dialogVisible.value = false;
        }
    });
};

// 删除用户
const handleDelete = (row: any) => {
     // 获取当前选中的行
     const selectedRows = tableData.value.filter(row => selectedRowKeys.value.includes(row.id));
    if (selectedRows.length === 0) {
        ElMessage.warning('请至少选择一项进行删除');
        return;
    }

    ElMessageBox.confirm(
        '确定要删除选中的用户吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 删除操作
        delete_User(selectedRows)
        ElMessage.success('删除成功');
    }).catch(() => { });
};

// 重置密码
const handleResetPassword = (row: any) => {
    ElMessageBox.confirm(
        '确定要重置该用户的密码吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        console.log('重置密码', row);
        ElMessage.success('密码重置成功');
    }).catch(() => { });
};

// 重置搜索表单
const handleReset = () => {
    searchForm.value = {
        keyword: '',
        username: '',
        phone: '',
        status: ''
    };
    // 这里可以根据需要重新加载表格数据
};
const fileInput=ref()
// 导入功能
const handleImport= ()=> {
   fileInput.value.click()
};
function handleFileChange(event) {
    const file = event.target.files[0];
    if (file) {
        const formData = new FormData();
        formData.append('file', file);
        uploadUser(formData);
    } else {
        ElMessage.error('未选择文件');
    }
}

// 导出功能
const handleExport = () => {
    const ws = XLSX.utils.json_to_sheet(tableData.value);  // 将 tableData 转为 sheet
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(data);
    const link = document.createElement('a');
    link.href = url;
    link.download = '用户数据.xlsx';  // 设置下载的文件名
    link.click();
    ElMessage.success('文件导出成功');
};

</script>

<style scoped></style>